package org.poem.controllerAdvice;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by poem on 2017/8/29.
 */
@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView exception(Exception exception, WebRequest request){
        ModelAndView modelAndView = new ModelAndView("error");//
        modelAndView.addObject("errorMessage",exception.getMessage());
        System.err.println("===========应用到所有@RequestMapping注解的方法，在其抛出UnauthenticatedException异常时执行");
        return  modelAndView;//返回一个逻辑试图
    }

    @ModelAttribute
    public void addAttributes(Model model){
        System.err.println("============应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model");
        model.addAttribute("msg","额外消息");
    }

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        System.err.println("============应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");
        webDataBinder.setDisallowedFields("id");//此处忽略掉request参数的id
    }


}
